package com.wuyu.mini.spring.mvc.servlet;

import com.wuyu.mini.spring.aop.aspect.MiniAspectWeaver;
import com.wuyu.mini.spring.ioc.MiniBeanInjector;
import com.wuyu.mini.spring.ioc.factory.MiniBeanFactory;
import com.wuyu.mini.spring.mvc.processor.ControllerRequestProcessor;
import com.wuyu.mini.spring.mvc.processor.JspRequestProcessor;
import com.wuyu.mini.spring.mvc.processor.PreRequestProcessor;
import com.wuyu.mini.spring.mvc.processor.RequestProcessor;
import com.wuyu.mini.spring.mvc.processor.RequestProcessorChain;
import com.wuyu.mini.spring.mvc.processor.StaticResourceRequestProcessor;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求转发器
 */
public class MiniDispatcherServlet extends HttpServlet {

    List<RequestProcessor> PROCESSOR = new ArrayList<RequestProcessor>();

    private final static String PACK="com.wuyu";

    @Override
    public void init(){
        //1.初始化容器
        MiniBeanFactory factory = MiniBeanFactory.MiniBeanFactoryHolder.SINGLETON.getInstance();
        factory.loadBeans(PACK);
        //注入
        MiniBeanInjector injector = new MiniBeanInjector();
        injector.doIoc();
        //切入
        MiniAspectWeaver weaver = new MiniAspectWeaver();
        weaver.doAop();
        //2.初始化请求处理器责任链
        PROCESSOR.add(new PreRequestProcessor());
        PROCESSOR.add(new StaticResourceRequestProcessor(getServletContext()));
        PROCESSOR.add(new JspRequestProcessor(getServletContext()));
        PROCESSOR.add(new ControllerRequestProcessor());
    }

    /**
     * 1.创建责任链对象实例
     * 2.通过责任链模式来依次调用请求处理器对请求进行处理
     * 3.对处理结果进行渲染
     * @param req
     * @param resp
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) {
        //1.创建责任链对象实例
        RequestProcessorChain requestProcessorChain = new RequestProcessorChain(PROCESSOR.iterator(), req, resp);
        //2.通过责任链模式来依次调用请求处理器对请求进行处理
        requestProcessorChain.doRequestProcessorChain();
        //3.对处理结果进行渲染
        requestProcessorChain.doRender();
    }
}
